package dbDrivers;

import java.util.ArrayList;
import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;

import mapper.dbinterface;

public class ldapConnection {

	
	
	// Xmlden alınacak veriler...
	String host;
	String Dn;
	String Pwd;
	String BaseDn;
	String attr;
	public ldapConnection() {
	

	config.Config.maine();
	host = config.Config.prop.getProperty("auth.ldap.location");
	Dn = config.Config.prop.getProperty("auth.ldap.managerBind");
	Pwd = config.Config.prop.getProperty("auth.ldap.managerPass");
	BaseDn = config.Config.prop.getProperty("auth.ldap.baseDn");
	attr = config.Config.prop.getProperty("auth.ldap.uidattr");
	// TODO Auto-generated constructor stub
}
	public Attributes ldapLogin(String userName, String userPassword) {
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, host); // XML^den alınacak
		env.put(Context.SECURITY_PRINCIPAL, attr+"=" + userName + "," + BaseDn); // XML'den
																				// alınacak
		env.put(Context.SECURITY_CREDENTIALS, userPassword);
		DirContext context = null;
		try {
			context = new InitialDirContext(env);
		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Attributes answer = null;
		try {
			answer = context.getAttributes("uid=" + userName + "," + BaseDn);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return answer;


	}

	public boolean ldapUserAdd(String userName, String userPassword,
			String group) {
		try {
			Hashtable env = new Hashtable();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, host);
			env.put(Context.SECURITY_PRINCIPAL, Dn);
			env.put(Context.SECURITY_CREDENTIALS, Pwd);

			DirContext context = new InitialDirContext(env);

			Attributes attrs = new BasicAttributes();
			BasicAttribute aa = new BasicAttribute("objectClass");
			aa.add("account");
			aa.add("simpleSecurityObject");
			attrs.put(aa);
			attrs.put("uid", userName);

			attrs.put("description", group);
			attrs.put("userPassword", userPassword.getBytes());

			context.createSubcontext("uid=" + userName + "," + BaseDn, attrs);
			System.out.println("LDAP sunucusunda kullanici kayit islemi basariyla gerceklesmistir.");
			return true;
		} catch (Exception e) {
			System.out.println("LDAP sunucusunda kullanici kayit islemi basarisizlikla sonuclanmistir.");
			return false;
		}

	}
	public void ldapSearch(){}
}
